#!/bin/bash

echo "========================================"
echo "PostgreSQL 数据库初始化脚本"
echo "========================================"
echo ""

echo "📋 此脚本将帮助您："
echo "   1. 创建PostgreSQL数据库"
echo "   2. 创建用户和权限"
echo "   3. 初始化扩展"
echo ""

echo "⚠️  请确保PostgreSQL已安装并运行"
echo ""

read -p "按Enter继续..."

echo ""
echo "========================================"
echo "【步骤1】创建数据库"
echo "========================================"
echo ""

read -p "请输入PostgreSQL管理员用户名（通常是 postgres）: " PG_USER
read -p "请输入数据库名称（默认: openharmony_knowledge）: " DB_NAME
DB_NAME=${DB_NAME:-openharmony_knowledge}

read -p "请输入数据库用户名（默认: knowledge_user）: " DB_USER
DB_USER=${DB_USER:-knowledge_user}

read -sp "请输入数据库用户密码: " DB_PASSWORD
echo ""

echo ""
echo "========================================"
echo "【步骤2】执行SQL命令"
echo "========================================"
echo ""

echo "正在创建数据库和用户..."
echo ""

psql -U "$PG_USER" -c "CREATE DATABASE $DB_NAME;" 2>/dev/null || echo "⚠️  数据库可能已存在，继续..."

psql -U "$PG_USER" -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASSWORD';" 2>/dev/null || echo "⚠️  用户可能已存在，继续..."

psql -U "$PG_USER" -d "$DB_NAME" -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;"
psql -U "$PG_USER" -d "$DB_NAME" -c "CREATE EXTENSION IF NOT EXISTS pg_trgm;"
psql -U "$PG_USER" -d "$DB_NAME" -c "ALTER DATABASE $DB_NAME SET shared_buffers = '256MB';"
psql -U "$PG_USER" -d "$DB_NAME" -c "ALTER DATABASE $DB_NAME SET work_mem = '16MB';"

echo ""
echo "========================================"
echo "✅ 数据库初始化完成！"
echo "========================================"
echo ""
echo "📝 请设置以下环境变量："
echo "   export DB_URL=jdbc:postgresql://localhost:5432/$DB_NAME"
echo "   export DB_USERNAME=$DB_USER"
echo "   export DB_PASSWORD=$DB_PASSWORD"
echo ""

